from django.contrib.auth.models import AbstractUser
from django.db import models

# 1. 定义拓展的用户模型
from django.forms import model_to_dict


class User(AbstractUser):
    mobile = models.CharField('手机号码', max_length=11, unique=True)
    email_active = models.BooleanField('邮箱是否激活', default=False)
    default_address = models.ForeignKey(
        'users.Address', related_name='users', verbose_name='默认地址', on_delete=models.SET_NULL, null=True)

    class Meta:
        db_table = 'tb_users'
        verbose_name = '用户'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.username + '-' +  self.mobile


# 2. 定义用户的收货地址的模型
class Address(models.Model):
    user = models.ForeignKey(
        User, verbose_name='所属用户', on_delete=models.CASCADE)
    title = models.CharField('标题', max_length=32)
    receiver = models.CharField('收件人', max_length=32)
    province = models.ForeignKey(
        'areas.Area', related_name='province_address', verbose_name='省', on_delete=models.SET_NULL, null=True)
    city = models.ForeignKey(
        'areas.Area', related_name='city_address', verbose_name='市', on_delete=models.SET_NULL, null=True)
    district = models.ForeignKey(
        'areas.Area', related_name='district_address', verbose_name='区县', on_delete=models.SET_NULL, null=True)
    place = models.CharField('详细地址', max_length=128)
    mobile = models.CharField('手机号码', max_length=11)
    tel = models.CharField('固定电话', max_length=11, blank=True)
    email = models.EmailField('邮箱', max_length=11, blank=True)
    is_deleted = models.BooleanField('是否删除', default=False)
    update_time = models.DateTimeField('修改时间', auto_now=True)

    class Meta:
        db_table = 'tb_address'
        verbose_name = '收货地址'
        verbose_name_plural = verbose_name
        # ordering = ['-update_time']
        ordering = ['-users', '-update_time']

    def __str__(self):
        return self.title

    def to_dict(self):
        # 把地址的实例对象转成字典的方法
        addresse_dict = model_to_dict(self,  exclude=['is_deleted', 'user'])
        addresse_dict['province'] = self.province.name
        addresse_dict['city'] = self.city.name
        addresse_dict['district'] = self.district.name
        addresse_dict['province_id'] = self.province.id
        addresse_dict['city_id'] = self.city.id
        addresse_dict['district_id'] = self.district.id
        return addresse_dict
